import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

//Services
import { CompanyRiskService } from './companyRisk.service';
import { GAService } from '../shared/services/ga.service';
import { UtilsService } from '../shared/services/utils.service';
import { AnalyticsService } from '../shared/services/analytics.service'

//Models
import { environment } from '../../environments/environment';
import { GoogleAnalyticsBeacon } from '../models/googleAnalytics.beacon'

@Component({  
  selector: 'app-root',
  templateUrl: './companyRisk.component.html',
  styleUrls: ['./companyRisk.component.css'],
  providers: [CompanyRiskService, UtilsService]
})
export class CompanyRiskComponent implements OnInit, OnDestroy{
  // Private properties for binding
  private sub: any;
  private companyId: string; 
  public readonly resourcesUrl: string = environment.resourcesUrl;
  public coverageEntityName: string;
  public isCoverageEntity: boolean;
  private meiId: string;
  public company: any = {};
  public mei: any = {};

  constructor(
    private route: ActivatedRoute,
    private riskService: CompanyRiskService,
    private gaService: GAService,
    private analyticsService: AnalyticsService) {              
  }

  //read url parameters
  ngOnInit(){
    this.sub = this.route.params.subscribe(params => {
      this.companyId = params['company'];
      this.coverageEntityName = params['coverageEntityName'];
      this.isCoverageEntity =  this.coverageEntityName != "NotApplicable"
    }); 

    this.getCompany();
  }  

  ngOnDestroy() {
    this.sub.unsubscribe();
  } 

  private getCompany(): void {
    this.riskService.company = this.riskService.getCompanyById(this.companyId);
    this.riskService.company.then((data) => {  
        this.company = data;      
        //if not available from various reasons, remove preloader because a static message will be displayed
        if(this.company.availability != 1)
          this.gaService.hidePreloader();
    })
    .catch((msg) => console.log(msg));
  }  

  public downloadCompanyRiskReport(): void {
    if(this.companyId){
      this.riskService.downloadReport(this.companyId, UtilsService.getCompanyUrlFriendlyName(this.company), false);
      this.analyticsService.sendBeacon(new GoogleAnalyticsBeacon('ESG RR Download PDF', 'ESG Risk Rating', { CompanyId: this.companyId }));
    }
  }

  public downloadCompanyRiskSummaryReport(): void {       
    if(this.companyId){
      this.riskService.downloadReport(this.companyId, UtilsService.getCompanyUrlFriendlyName(this.company), true);    
      this.analyticsService.sendBeacon(new GoogleAnalyticsBeacon('ESG RR Download Summary PDF', 'ESG Risk Rating', { CompanyId: this.companyId }));
    }
  }

  public addToPortfolio(): void {
    if(this.companyId && this.company)
      this.riskService.addToPortfolio(this.companyId, this.company.companyName, this.company.exchangeTicker);    
  }
}
